package com.atwisdom.star.core.bsl.customized.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.vo.ActionData;
import com.atwisdom.star.common.vo.JsonResult;
import com.atwisdom.star.common.vo.ResultInfo;
import com.atwisdom.star.core.bsl.customized.SaleBslService;
import com.atwisdom.star.core.bsl.modelClass.logic.Impl.LogicInstanceBslServiceImpl;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierInstance;
import com.atwisdom.star.core.dsl.modelClass.hier.HierInstanceDslService;
import com.atwisdom.star.core.dsl.modelClass.logic.LogicInstanceDslService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 
 * @Date: 2023-08-28 10:54
 */
@Slf4j
@AllArgsConstructor
@Service
public class SaleBslServiceImpl implements SaleBslService {
    private LogicInstanceDslService logicInstanceDslService;
    private HierInstanceDslService hierInstanceDslService;

    private LogicInstanceBslServiceImpl logicInstanceBslService;

    /**
     * 根据采购计划明细，查询供应商价表
     * @return
     */
    @Override
    public JSONObject queryCustomerPrice(Integer customerId, String materialBcode)  {
        List<JSONObject> customerPriceList = logicInstanceDslService.query("effectiveStatus = 1 and customer_id = " + customerId,
                "customerPrice", null, "parentId = 'root' and material_bcode = '"+materialBcode+"'","root");
        if (CollectionUtil.isEmpty(customerPriceList)) {
            return null;
        }
        JSONArray hierArray = customerPriceList.get(0).getJSONObject("hier").getJSONArray("content");
        if (CollectionUtil.isEmpty(hierArray)) {
            return null;
        }
        return hierArray.getJSONObject(0).getJSONObject("values");
    }


    @Transactional(rollbackFor = Exception.class)
    public ResultInfo<?> updateSaleOrderPrice(ActionData<JSONObject> actionData) {
        String model = actionData.getModel();
        Long containerId = actionData.getInstanceId();
        String parentNodeId = actionData.getParentId();
        // 查询主表记录
        JSONObject logicInstanceJson = logicInstanceDslService.queryJsonById(containerId);
        JSONObject values = logicInstanceJson.getJSONObject("values");
        Integer customerId = values.getInteger("customer_id");

        List<HierInstance> hierInstances = hierInstanceDslService.fetchByParentNodeId(model, containerId, parentNodeId);
        final BigDecimal[] totalAmount = {BigDecimal.ZERO};
        hierInstances.forEach(hIns -> {
            JSONObject childValues = hIns.getValues();
            String materialBcode = childValues.getString("material_bcode");
            BigDecimal price = childValues.getBigDecimal("price");
            JSONObject customerPriceValues = this.queryCustomerPrice(customerId, materialBcode);
            if (price == null || price.compareTo(BigDecimal.ZERO) == 0 ) {
                price = customerPriceValues == null ? BigDecimal.ZERO : customerPriceValues.getBigDecimal("price");
            }

            BigDecimal priceNonTax = childValues.getBigDecimal("priceNonTax");
            if (priceNonTax == null || priceNonTax.compareTo(BigDecimal.ZERO) == 0 ) {
                priceNonTax = customerPriceValues == null ? BigDecimal.ZERO : customerPriceValues.getBigDecimal("priceNonTax");
            }
            BigDecimal taxRate = childValues.getBigDecimal("taxRate");
            if (taxRate == null) {
                taxRate = customerPriceValues == null ? BigDecimal.ZERO : customerPriceValues.getBigDecimal("taxRate");
                taxRate = taxRate != null ? taxRate :  BigDecimal.ZERO;
            }

            childValues.put("price", price);
            childValues.put("priceNonTax", priceNonTax);
            childValues.put("taxRate", taxRate);
            BigDecimal quantity = childValues.getBigDecimal("quantity");
            quantity = quantity == null ? BigDecimal.ZERO : quantity;
            BigDecimal amount = quantity.multiply(price);
            BigDecimal moneyNonTax = quantity.multiply(priceNonTax);
            childValues.put("money", amount);
            childValues.put("moneyNonTax", moneyNonTax);
            totalAmount[0] = totalAmount[0].add(amount);
            hierInstanceDslService.updateById(hIns);
        });

        logicInstanceJson.getJSONObject("values").put("money", totalAmount[0]);
        logicInstanceDslService.updateById(logicInstanceJson);
        return JsonResult.success(logicInstanceJson);
    }



    public ResultInfo<?> createSaleQualityNotice(ActionData<JSONObject> actionData){




       return logicInstanceBslService.copyMasterAndHierList(actionData);
    }
}
